<template>
  <div class="attr">
    <!-- 上半部分 -->
    <Category @sendCategoryIds="getCategoryIds" @sendClearCategoryIds="clearCategoryIds"></Category>
    <!-- 下半部分 -->
    <!-- 展示属性 -->
    <el-card class="box-card" v-show="showAttrOrAddAttr">
      <el-button :disabled="isBtnDisabled" type="primary" icon="Plus" @click="addProductAttrValue">添加平台属性</el-button>
      <el-table border :data="productAttrValueList" style="width: 100%;margin:15px 0;">
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column prop="attrName" label="属性名称" width="200" />
        <el-table-column prop="attrValue" label="属性值名称"  width="">
          <template #="{row,$index}">
            <el-tag v-for="item,index in row.attrValueList" :key="index" type="success" style="margin:5px 5px;">{{item.valueName}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200">
          <template #="{row,$index}">
            <el-button type="warning" size="small" icon="edit" @click="editAttrValue(row)"></el-button>
            <!-- <el-button type="danger" size="small" icon="delete" @click="deleteAttrValue(row)"></el-button> -->
            <el-popconfirm :title="`确定要删除属性${row.attrName}吗?`" @confirm="deleteAttrValue(row)" confirm-button-text="确定" cancel-button-text="再想想">
              <template #reference>
                <el-button type="danger" size="small" icon="delete"></el-button>
              </template>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 添加属性 -->
    <el-card class="box-card" v-show="!showAttrOrAddAttr">
      <!-- 输入部分 -->
      <div class="card-input" style="margin:15px 0;">
        <span style="margin-right:15px;">属性名称</span>
        <el-input v-model="inputValue" placeholder="输入属性名称" style="width:200px;"></el-input>
      </div>
      <!-- 按钮部分 -->
      <div class="card-btn">
        <el-button type="primary" icon="Plus" @click="addAttr" :disabled="!inputValue">添加属性值</el-button>
        <el-button @click="cancelAddAttr">取消</el-button>
      </div>
      <!-- 属性展示部分 -->
      <el-table :data="saveAttrList" border style="width: 100%;margin:15px 0;">
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="属性值" width="">
          <template #="{row,$index}">
            <input ref="inputRef" type="text" v-model="row.valueName">
          </template>
        </el-table-column>
        <el-table-column label="操作" width="">
          <template #="{row,$index}">
            <el-button @click="deleteAttr(row.id)" type="warning" icon="delete" size="small"></el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 保存、取消按钮部分 -->
      <div class="card-btn">
        <el-button type="primary" @click="saveAddArrtValueList">保存</el-button>
        <el-button @click="cancelSaveAddArrtValueList">取消</el-button>
      </div>
    </el-card>
  </div>
</template>

<script setup lang="ts">
//@ts-ignore
import Category from "@/components/category/index.vue";
import { ElButton, ElCard, ElIcon, ElTable, ElTableColumn, ElTag, ElInput, ElMessage, ElPopconfirm } from "element-plus";
import { ArrowDown, Plus } from '@element-plus/icons-vue';
//@ts-ignore引入请求函数
import { reqProductAttrList, reqSaveProductAttr, reqDeleteProductAttr } from "@/api/product/index.ts";
//@ts-ignore
import type { responseProductAttrValue, productAttrObj } from "@/api/product/type.ts";
import { reactive, ref } from "vue";

//存储当前分类下的属性与属性值
let productAttrValueList = ref<productAttrObj[]>([]);
//添加平台属性按钮是否禁用
let isBtnDisabled = ref(true);
//展示属性值或者添加属性的el-card切换
let showAttrOrAddAttr = ref(true);
//一二三级分类选择的id，从子组件传递过来
let selectCategoryIds = reactive({
  category1Id:0,
  category2Id:0,
  category3Id:0
})

//获取当前分类下的商品属性
const getProductValueList = async (category1Id:number,category2Id:number,category3Id:number) => {
  let res:responseProductAttrValue = await reqProductAttrList(category1Id,category2Id,category3Id);
  if(res.code === 200){
    productAttrValueList.value = res.data;
    // console.log("当前分类下商品属性api成功",res);
  }
}

//商品属性的修改和删除按钮
const deleteAttrValue = async (attrValue) => {
  let res = await reqDeleteProductAttr(attrValue.id);
  if(res.code == 200){
    ElMessage({type:"success",message:"属性删除成功"});
    //发请求更新商品属性
    getProductValueList(selectCategoryIds.category1Id,selectCategoryIds.category2Id,selectCategoryIds.category3Id);
    // console.log("品牌属性删除api成功",res);
  }
}
const editAttrValue = (attrValue) => {
  showAttrOrAddAttr.value = false;
  //传递要修改属性的属性值
  inputValue.value = attrValue.attrName;
  saveAttrList.value = attrValue.attrValueList;
  attrValueLength = attrValue.attrValueList.length;  //修改属性是的属性值有多少
  //注意此处是浅拷贝，修改属性后没保存将会影响源数据
  //采用JSON.parse(JSON.stringfry())进行深拷贝
  // Object.assign(saveAttr,attrValue);
  Object.assign(saveAttr,JSON.parse(JSON.stringify(attrValue)));
}


//平台属性添加按钮
const addProductAttrValue = () => {
  showAttrOrAddAttr.value = false;
}

//平台属性添加部分
let inputRef = ref();  //dom原生input
let inputValue = ref(null);  //input框收集属性名称
let saveAttrList = ref<any>([]);  //属性值收集
let attrValueLength = 0;  //修改属性时的属性值有多少
//属性收集，要传递给服务器,添加属性或者修改属性
let saveAttr:any = reactive({
  categoryId:0,
  categoryLevel:0,
  attrName:"",
  attrValueList:[]
})

//取消添加属性按钮
const cancelAddAttr = () => {
  saveAttrList.value = [];
}
//添加属值按钮
const addAttr = () => {
  if(inputValue.value == undefined) return;
  let attrObj = {
    valueName:"",
    id:new Date().getTime()  //新添加属性,用于唯一标识，待会要删除
  };
  //attrObj的value当前未收集
  saveAttrList.value.push(attrObj);
  //当前input框要获取焦点
  setTimeout(()=>{
    inputRef.value.focus();
  },300)
}
//删除属性值按钮
const deleteAttr = (id:number) => {
  saveAttrList.value = saveAttrList.value.filter(item => {
    return item.id !== id;
  })
}
//新添加或修改属性保存与取消按钮
const saveAddArrtValueList = () => {
  let str = "添加";  //默认添加属性
  //进行参数整理(修改属性)
  //进行参数整理(添加属性)
  if(saveAttr.categoryId == 0){
    //添加属性
    saveAttr.categoryId =  productAttrValueList.value[0].categoryId;
    saveAttr.categoryLevel =  productAttrValueList.value[0].categoryLevel;
    saveAttr.attrName = inputValue.value;
    //清除后添加的flag,id属性
    saveAttrList.value.forEach(item => {
      // delete(item.flag);
      delete(item.id);
    })
  } else {
    //修改属性
    str = "修改";
    //判断修改属性前的属性值有多少个,需要对后添加的属性值删除id值
    for(let i=attrValueLength-1;i<saveAttrList.value.length;i++){
      delete(saveAttrList.value[i].id);
    }
  }
  saveAttr.attrValueList = saveAttrList.value;  //追加属性值或者更新属性值
  saveProductAttrValue(saveAttr,str);  //发请求存储新属性
  //关闭当前页面
  cancelSaveAddArrtValueList();
  //发请求获取最新商品属性
  setTimeout(()=>{
    getProductValueList(selectCategoryIds.category1Id,selectCategoryIds.category2Id,selectCategoryIds.category3Id);
  },300)
}
const cancelSaveAddArrtValueList = () => {
  showAttrOrAddAttr.value = true;
  inputValue.value = null;
  saveAttrList.value = [];
  attrValueLength = 0;
  saveAttr = {
    categoryId:0,
    categoryLevel:0,
    attrName:"",
    attrValueList:[]
  }
}


//添加平台属性请求
const saveProductAttrValue = async (paramsObj:productAttrObj,str:string) => {
  let res = await reqSaveProductAttr(paramsObj);
  if(res.code == 200){
      ElMessage({type:"success",message:`属性${str}成功`});
      // console.log('平台属性添加api成功',res);
  }
}

//自定义事件部分
//从组件category获取选的的三级分类对应的id
const getCategoryIds = (categoryIds) => {
  selectCategoryIds = categoryIds;  //存储一下
  // console.log(categoryIds);  //获取到对应的id值了
  //发请求获取商品属性
  getProductValueList(selectCategoryIds.category1Id,selectCategoryIds.category2Id,selectCategoryIds.category3Id);
  //解禁按钮
  isBtnDisabled.value = false;
}
//组件category的一二级分类id改变的自定义事件
const clearCategoryIds = () => {
  //按钮禁用
  isBtnDisabled.value = true;
  //清空表格数据
  productAttrValueList.value = [];
  // console.log('一二级id改变了');
}
</script>
<script lang="ts">
export default {
  name:"Attr"
}
</script>

<style scoped lang="scss">
//对本组件的input框进行美化
input{
  width:100%;
  height: 100%;
  border:none;
  outline: none;

  &:hover{
    background-color: #f5f7fa;
  }
}
</style>